package com.example.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.example.service.FileService;
import com.example.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.EDNPOINT;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        String accessKeyId=ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret=ConstantOssPropertiesUtils.SECRECT;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            // 获取文件名称。
            //生成UUID 添加到文件名称
            String uuid = UUID.randomUUID().toString().replace("-","");
            String fileName=file.getOriginalFilename();
            fileName=uuid+"@"+fileName;
            //按照当前日期 创建文件夹 上传到创建文件夹里面
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName=timeUrl+"/"+fileName;

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭ossClient
            ossClient.shutdown();
            //获得上传之后文件路径
            String url= "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;

        } catch (IOException e) {
            throw new RuntimeException(e);


        }
    }
}
